package adminorg;


import com.vaadin.Application;
import com.vaadin.ui.*;
import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;

//import com.vaadin.ui.themes.Runo;
import adminorg.CompanyForm;

import com.vaadin.terminal.ExternalResource;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import com.vditl.core.DVLog;
import com.oros.utils.*;
//import org.vaadin.openid.OpenIdHandler;
//import org.vaadin.openid.OpenIdHandler.UserAttribute;


public class AdminorgApplication extends Application implements RegistrationUnit {
	
	private static final long serialVersionUID = -1475930354942430792L;
	private AbsoluteLayout mainLayout;
	private TabSheet MainTabSheet;
	private CompanyForm compaccordion;
	private OrgForm orgForm;
	private DocumentForm documentForm;
	private DictionaryForm dictionaryForm;
	private BPEventForm bpEventForm;
	private BPAdminForm bpAdminForm;
	private StatisticUse statisticuseForm;
	private StatisticData statisticForm;
	private Window mainWindow; 
	private DatabaseHelper dbHelp = new DatabaseHelper(this);
	
	@Override
	public Application getApplication()
	{
		return this;
	}
	
	@Override
	public void init() {
		try
		{
		   setLocale(((WebApplicationContext)getContext())
		            .getBrowser().getLocale());
			dbHelp.setResources("adminorg.resources.Adminorg");
			GAERegistration registration = new GAERegistration(this);
			registration.init();
		} catch(Exception e)
		{
			e.printStackTrace();
			mainWindow = new Window("Error");
		    mainLayout.addComponent(authInfo = new HorizontalLayout());
			Label err = new Label("Извините, попробуйте немного позже, поскольку возникла проблема\n");
			mainWindow.addComponent(err);
			err = new Label("Вибачте, спробуйте пізніше, тому що виникла помилка\n");
			mainWindow.addComponent(err);
			err = new Label("Sorry, please try again later, the service is temporarily unavailable\n");
			mainWindow.addComponent(err);
			err = new Label("Error: "+e.getMessage());
			mainWindow.addComponent(err);
	        setMainWindow(mainWindow);
		}
	}
	public DocumentForm getDocumentForm() { return documentForm;}
	@Override
	public void minimum_initMainAppForm() {

		try
		{
		  setTheme("adminorgtheme");
		  mainLayout = new AbsoluteLayout();
		  mainLayout.setWidth("100%");
		  mainLayout.setHeight("1000px");
		  mainLayout.setMargin(false);	     
		  resetMainLayout();
		  mainWindow = new Window(dbHelp.getWords("OrganizationChartAdmin"),mainLayout);
		  mainWindow.setSizeFull();
		  mainWindow.setScrollable(true);
		  mainWindow.setContent(mainLayout);
		  setMainWindow(mainWindow);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			mainWindow = new Window("Server Error");
		    mainLayout.addComponent(authInfo = new HorizontalLayout());
			Label err = new Label(dbHelp.getWords("ServerError"));
			mainWindow.addComponent(err);
			err = new Label("Error: "+e.getMessage());
			mainWindow.addComponent(err);
	        setMainWindow(mainWindow);
	    }
		
	}
	
	private void buildMainTab() throws Exception {
		MainTabSheet = new TabSheet();
		MainTabSheet.setImmediate(true);
		MainTabSheet.setWidth("100.0%");
		MainTabSheet.setHeight("100.0%");
		dbHelp.resetCompanyListeners();
		compaccordion = new CompanyForm(dbHelp);
		orgForm = new OrgForm(dbHelp);
		documentForm = new DocumentForm(dbHelp);
		dictionaryForm = new DictionaryForm(dbHelp);
		bpEventForm = new BPEventForm(dbHelp);
		bpAdminForm = new BPAdminForm(dbHelp);
		statisticuseForm = new StatisticUse(dbHelp);
		statisticForm = new StatisticData(dbHelp);
		MainTabSheet.addTab(compaccordion.getCompanyForm(), dbHelp.getWords("Organizations"), null);
		MainTabSheet.addTab(orgForm.getOrgForm(), dbHelp.getWords("OrganizationChart"), null);
		MainTabSheet.addTab(documentForm.getDocumentForm(), dbHelp.getWords("Documents"), null);
		MainTabSheet.addTab(dictionaryForm.getDictionaryForm(),dbHelp.getWords("Dictionary"),null);
		MainTabSheet.addTab(bpEventForm.getBPEventForm(),dbHelp.getWords("Events"),null);
		MainTabSheet.addTab(bpAdminForm.getBPAdminForm(),dbHelp.getWords("BPAdministration"),null);
		MainTabSheet.addTab(statisticuseForm.getStatisticUseForm(),dbHelp.getWords("AppointmentStatistics"),null);
		MainTabSheet.addTab(statisticForm.getStatisticForm(),dbHelp.getWords("Statistics"),null);
        resetMainLayout();
		mainLayout.addComponent(MainTabSheet,"top:10px");
	}

	private void resetMainLayout()
	{
        mainLayout.removeAllComponents();
		if (authInfo==null) authInfo = new HorizontalLayout();
	    mainLayout.addComponent(authInfo,"left:800px");
	}


	private HorizontalLayout authInfo;
    private String lastPage,lastSubpage;
    private Integer lastCompany;
    private void setLastPageInfo()
    {
		lastSubpage=null;
    	if (lastPage!=null)
		{
			lastPage=lastPage.trim();
			//String lastSubpageIndex=null,lastSubsubpage=null;
			int pos = lastPage.indexOf('.');
			if (pos>0)
			{
				lastSubpage = lastPage.substring(pos+1);
				lastPage = lastPage.substring(0,pos);
				/********** future development
				pos = lastSubpage.indexOf('.');
				if (pos>0)
				{
					lastSubsubpage=lastSubpage.substring(pos+1);
					lastSubpage = lastSubpage.substring(0,pos);
				}
				pos = lastSubpage.indexOf(':');
			    if (pos>0)
			    {
			    	lastSubpageIndex = lastSubpage.substring(pos+1);
			    	lastSubpage = lastSubpage.substring(0,pos);
			    }
			    **************************/
			}
		}    	
    }
    private void setTabVisibility()
    {
        if (dbHelp.isUserSuperAdmin())    	
        {
			MainTabSheet.getTab(0).setVisible(true);
        }
        else
        {
			MainTabSheet.getTab(0).setVisible(false);
        }
        if (dbHelp.isCompAccPropertySetForAnyCompany("isprocessadmin")
        		||dbHelp.isCompAccPropertySetForAnyCompany("isstatadmin")
        		||dbHelp.isCompAccPropertySetForAnyCompany("isadmin"))
        {
        	MainTabSheet.getTab(3).setVisible(true);
        }
        else
        {
        	MainTabSheet.getTab(3).setVisible(false); //!!! Additional checks must be done!!!
        }
        if (dbHelp.isCompAccPropertySetForAnyCompany("isprocessadmin"))
        {
        	MainTabSheet.getTab(4).setVisible(true);
        	MainTabSheet.getTab(5).setVisible(true);
        }
        else
        {
        	MainTabSheet.getTab(4).setVisible(false);
        	MainTabSheet.getTab(5).setVisible(false);
        }
        if (dbHelp.isCompAccPropertySetForAnyCompany("isstatadmin"))
        {
        	MainTabSheet.getTab(6).setVisible(true);
        }
        else
        {
        	MainTabSheet.getTab(6).setVisible(false);
        }
        
        	
    }
	private void setCurrentTabs() throws Exception
	{
		if (lastCompany!=null && dbHelp.getCompContainer().getDistinctColumnValues("id").contains(lastCompany))
		{
			System.out.println("currentCompany set to "+lastCompany);
			dbHelp.setCompanyId(lastCompany);
		}
		setTabVisibility();
		if (lastPage!=null)
		{
			System.out.println("switching to company["+lastCompany+"] page["+lastPage+"]["+lastSubpage+"]");
			if (lastPage.length()>0)
			{
				if (lastPage.equals("documents"))
				{
					if (MainTabSheet.getTab(2).isVisible())
					{
						MainTabSheet.setSelectedTab(MainTabSheet.getTab(2).getComponent());
					    if (lastSubpage!=null && lastSubpage.length()>0)
					    {
						    documentForm.setDocRightEntry(lastSubpage);
					    }
					}
			
				} else if (lastPage.equals("orgschema"))
				{
					if (MainTabSheet.getTab(1).isVisible())
					    MainTabSheet.setSelectedTab(MainTabSheet.getTab(1).getComponent());
				} else if (lastPage.equals("dictionary"))
				{
					if (MainTabSheet.getTab(3).isVisible())
					    MainTabSheet.setSelectedTab(MainTabSheet.getTab(3).getComponent());
				} else if (lastPage.equals("companies"))
				{
					if (MainTabSheet.getTab(0).isVisible())
					{
						 MainTabSheet.setSelectedTab(MainTabSheet.getTab(0).getComponent());
					     if (lastSubpage!=null && lastSubpage.equals("compacc"))
					     {
						     compaccordion.setCompAccEntryPoint();
					     }
					}
				} else if (lastPage.equals("bpevent"))
				{
					if (MainTabSheet.getTab(4).isVisible())
					    MainTabSheet.setSelectedTab(MainTabSheet.getTab(4).getComponent());
				} else if (lastPage.equals("bpadmin"))
				{
					if (MainTabSheet.getTab(5).isVisible())
					  MainTabSheet.setSelectedTab(MainTabSheet.getTab(5).getComponent());
				} else if (lastPage.equals("appstatistic"))
				{
					if (MainTabSheet.getTab(6).isVisible())
					  MainTabSheet.setSelectedTab(MainTabSheet.getTab(6).getComponent());
				} else if (lastPage.equals("statistic"))
				{
					if (MainTabSheet.getTab(5).isVisible())
					  MainTabSheet.setSelectedTab(MainTabSheet.getTab(7).getComponent());
				}

			}
		}
		if (MainTabSheet!=null)
		{
			MainTabSheet.addListener(new TabSheet.SelectedTabChangeListener() {
				/**
				 * 
				 */
				private static final long serialVersionUID = -681456625546829388L;

				@Override
				public void selectedTabChange(SelectedTabChangeEvent event) {
					int pos = MainTabSheet.getTabPosition(MainTabSheet.getTab(MainTabSheet.getSelectedTab()));
					String pagename=null;
					switch(pos)
					{
					case 0:
						pagename="companies";
						break;
					case 1:
						pagename="orgschema";
						break;
					case 2:
						pagename="documents";
						break;
					case 3:
						pagename="dictionary";
						break;
					case 4:
						pagename="bpevent";
						break;
					case 5:
						pagename="bpadmin";
						break;
					case 6:
						pagename="appstatistic";
						break;
					case 7:
						pagename="statistic";
						break;		
					}
					if (pagename!=null) try
							{
						       dbHelp.getCurrentUserTrackItem().getItemProperty("last_page").setValue(pagename);
						       dbHelp.saveCurrentUserTrackInfo();
							}
					       catch(Exception e)
					       {
					    	   e.printStackTrace();
					       }
					
				}
			});
		}
	}
	private String getUserNotPermittedReason(String userName)
	{
		try
		{
		  dbHelp.setNewUser(userName);	
		  dbHelp.refreshAll();
		  dbHelp.getUserTrackContainer(userName);
		  lastCompany=(Integer)dbHelp.getCurrentUserTrackItem().getItemProperty("last_company").getValue();
		  lastPage=(String)dbHelp.getCurrentUserTrackItem().getItemProperty("last_page").getValue();
		  setLastPageInfo();
		  if (dbHelp.isSuperAdminEmail(userName))
		  {
			dbHelp.setSuperAdmin(true);
			dbHelp.getCompContainer().removeAllContainerFilters();
			return null;
		  } else dbHelp.setSuperAdmin(false);
		  if (dbHelp.setCompUserContainer(userName))
		  {
			  return null;  
		  }
		} catch(Exception e)
		{
			e.printStackTrace();
			return dbHelp.getWords("ServerError")+": "+e.getMessage();
		}
		return dbHelp.getWords("YouAreNotRegisteredYetForAnyCompany");
	}
	private HorizontalLayout authCentralInfo=null;
	private VerticalLayout debugLayout;
	private void addAuthInfo(String addMessage)
	{
         		resetMainLayout();debugLayout=null;
				authCentralInfo=new  HorizontalLayout();
				String welcomeMessage =dbHelp.getWords("WelcomeMessage");
				if (addMessage!=null) welcomeMessage=welcomeMessage+"<BR>"+addMessage;
				Label labelInfo=new Label("<span align=\"center\">"+welcomeMessage+"</span>",Label.CONTENT_XHTML);
                authCentralInfo.addComponent(labelInfo);
                authCentralInfo.setComponentAlignment(labelInfo, Alignment.MIDDLE_CENTER);
				mainLayout.addComponent(authCentralInfo, "left:400px;top:200px");
	}
	@Override
    public boolean isAuthetincationFormAlreadyBuilt()
    {
    	return authInfo.getComponentIterator().hasNext();
    }
	public void showDebugInfo(String s)
	{
		if (debugLayout==null)
		{
			debugLayout = new VerticalLayout();
			debugLayout.setHeight("3000px");
			Panel scrollableTableAndFormPanel = new Panel();
			scrollableTableAndFormPanel.setScrollable(true);
			scrollableTableAndFormPanel.setImmediate(true);
			scrollableTableAndFormPanel.addComponent(debugLayout);
			scrollableTableAndFormPanel.setHeight("300px");
			mainLayout.addComponent(scrollableTableAndFormPanel, "left:400px;top:260px");
		}
		Label debug = new Label(s);
		debugLayout.addComponent(debug);
	}
	public void debugFullError(Throwable e) {
	      while (e!=null) {
	          debugStackInfo(e);
	          e=e.getCause();
	          if (e!=null) showDebugInfo(" CAUSED BY: "+e.getMessage());
	      }
    }

	public void debugStackInfo(Throwable e) {
	      StackTraceElement[] trace=e.getStackTrace();
	      for(int i=0;i<trace.length;i++)
	          showDebugInfo(trace[i].toString()+ " in "+trace[i].getFileName()+" ("+trace[i].getLineNumber()+")");
	}

    @Override
	public void showFormForRegisteredUser(String userName,String userEmail,boolean isInternalUserAdmin,
			String logoutURL)
	{
		authInfo.removeAllComponents();
        String reasonNotPermit = getUserNotPermittedReason(userName);
		if (reasonNotPermit==null)
        {
			try
			{
        	  buildMainTab();
        	  setCurrentTabs();
        	  dbHelp.checkCompanyDocumentList();
			} catch(Throwable e)
			{
				e.printStackTrace();
				String err=e.getMessage();
				addAuthInfo("Error:"+err);
				debugFullError(e);
			}
        }
        else
        {
        	addAuthInfo(reasonNotPermit);
        }
		Label email = new Label(userName+" &nbsp;&nbsp; ",Label.CONTENT_XHTML);
		Link link = new Link(dbHelp.getWords("logout"), new ExternalResource(logoutURL));
		email.setStyleName("email");
		authInfo.addComponent(email);
		authInfo.addComponent(link);
	}
    @Override
    public void showFormForUnregisteredUser(String logoutName,String loginURL)
    {
		authInfo.removeAllComponents();
		Link link;
		addAuthInfo(null);
		if (logoutName != null) {
			mainWindow.showNotification(dbHelp.getWords("Bye")+" "+ logoutName);
		}
		link = new Link(dbHelp.getWords("login"), new ExternalResource(loginURL));
		authInfo.addComponent(link);
    }
}
